package com.shaozi.nc.rpc;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;

import com.shaozi.lib.request.BaseRequest;
import com.shaozi.lib.request.RequestCallback;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.manage.bean.CheckUpdateCompany;
import com.shaozi.utils.common.JsonUtil;
import com.shaozi.utils.http.HttpBase;

@Deprecated
public class UserInfoHttp extends HttpBase implements BaseRequest {

	private Logger logger = Logger.getLogger(UserInfoHttp.class);
	@Value("${sys.platform.api.version:v1.3.0}")
	private String version;
	@Value("${sys.info.api}")
	private String domain;

	public UserInfoHttp() {
		super();
	}

	@Override
	public String getDomain() {
		return domain;
	}

	@Override
	public String getUrl() {
		return "Server/UserRest/listOfCompany";
	}

	@Override
	public void doRequest(RequestCallback callback, Object... params) {
		String companyId = (String) params[0];
		long identity = (long) params[1];
		String uri_end = this.getUrl() + "?company_id=" + companyId + "&identity=" + identity;
		String uri = String.format("%s%s", getDomain(), uri_end);
		Map<String, String> headers = new HashMap<>();
		headers.put("sz-version", version);
		try {
			doAsyncGet(uri, headers, new FutureCallback<HttpResponse>() {
				@Override
				public void cancelled() {
					logger.error("request is cancelled,companyId:" + companyId);
					callback.callback(false, null);
				}

				@Override
				public void completed(HttpResponse resp) {
					String s = null;
					try {
						s = EntityUtils.toString(resp.getEntity());
					} catch (ParseException e) {
						logger.error(e);
					} catch (IOException e) {
						logger.error(e);
					}
					JSONObject jsonObj = new JSONObject(s).getJSONObject("data");
					CheckUpdateCompany updateCompany = null;
					if (jsonObj != null) {
						try {
							updateCompany = JsonUtil.toObject(jsonObj.toString(), CheckUpdateCompany.class);
						} catch (SzException e) {
							logger.error(e);
						}
					}
					callback.callback(true, updateCompany);
				}

				@Override
				public void failed(Exception arg0) {
					logger.error(arg0);
					callback.callback(false, arg0);
				}

			});
		} catch (IOReactorException e) {
			logger.error(e);
		}
	}
}
